﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DB_Test.ServiceReference1;
using Microsoft.Win32;
using System.Globalization;

namespace DB_Test
{
	/// <summary>
	/// Interaction logic for OrderViewPanel.xaml
	/// </summary>
	public partial class ProductViewPanel : UserControl
	{
		#region Constants
		private const string DEFAULT_IMAGE_PATH = "pack://application:,,,/DB_Test;component/Resources/images1.png";
		#endregion

		#region Initialization
		public ProductViewPanel()
		{
			InitializeComponent();
			IsVisibleChanged += new DependencyPropertyChangedEventHandler(ProductViewPanel_IsVisibleChanged);
		}
		#endregion

		#region Properties

		public bool IsEditing
		{
			get
			{
				return (bool)GetValue(IsEditingProperty);
			}
			set
			{
				SetValue(IsEditingProperty, value);
			}
		}
		public bool ShoudUpdateDB
		{
			get
			{
				return (bool)GetValue(ShoudUpdateDBProperty);
			}
			set
			{
				SetValue(ShoudUpdateDBProperty, value);
			}
		}
		#endregion

		#region Dependency properties
		internal static readonly DependencyProperty ShoudUpdateDBProperty
			= DependencyProperty.Register("ShoudUpdateDB", typeof(bool), typeof(ProductViewPanel));
		internal static readonly DependencyProperty IsEditingProperty
			= DependencyProperty.Register("IsEditing", typeof(bool), typeof(ProductViewPanel), new PropertyMetadata(true));
		#endregion

		#region Implementation
        
        private void BrowseButton_Click(object sender, RoutedEventArgs args)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Images (*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*PNG|All files (*.*)|*.*";

            if (dlg.ShowDialog().Value)
            {
                xProductImagePath.Text = dlg.FileName;
            }
        }

		private void SaveButton_Click(object sender, RoutedEventArgs e)
		{
			if (HasErrors())
			{
				return;
			}

			decimal unitPrice;
			decimal.TryParse(xUnitPriceTxt.Text, out unitPrice);

			short unitsInStock;
			short.TryParse(xUnitsInStockTxt.Text, out unitsInStock);

			short unitsOnOrder;
			short.TryParse(xUnitsOnOrderTxt.Text, out unitsOnOrder);

			short reorderLevel;
			short.TryParse(xReorderLevelTxt.Text, out reorderLevel);

			bool discounted;
			bool.TryParse(xDiscontinuedTxt.Text, out discounted);

			var client = new WCFServiceClient();
			try
			{
				client.Open();

				ProductsClass product = new ProductsClass
				{
					Discontinued = discounted,
					ProductName = xProductNameTxt.Text,
					QuantityPerUnit = xQuantityPerUnitTxt.Text,
					ReorderLevel = reorderLevel,
					UnitPrice = unitPrice,
					UnitsInStock = unitsInStock,
					UnitsOnOrder = unitsOnOrder
				};

				Uri imageUri;
				if (!string.IsNullOrEmpty(xProductImagePath.Text))
				{
					imageUri = new Uri(xProductImagePath.Text);
				}
				else
				{
					imageUri = new Uri(DEFAULT_IMAGE_PATH);
				}

				BitmapImage image = new BitmapImage(imageUri);
				if (image != null)
				{
					ByteArrayToImageConverter conv = new ByteArrayToImageConverter();
					product.Logo = (byte[])conv.ConvertBack(image, typeof(byte[]), null, CultureInfo.CurrentCulture);
				}

				if (IsEditing)
				{
					client.EditProduct(product);
				}
				else
				{
					client.AddProduct(product);
				}
			}
			finally
			{
				client.Close();
			}

			ShoudUpdateDB = true;
			ClearInputExt();
            UpdateDataContex();
		}

		private bool HasErrors()
		{
			return Validation.GetErrors(xProductNameTxt).Count > 0;
		}

        private void UpdateDataContex()
        {
            DataContext = new ProductsClass();
        }

		internal void ClearInput()
		{
			xProductImagePath.Text = "";
			xProductNameTxt.ClearValue(TextBlock.TextProperty);
			xQuantityPerUnitTxt.ClearValue(TextBlock.TextProperty);
			xUnitPriceTxt.ClearValue(TextBlock.TextProperty);
			xUnitsInStockTxt.ClearValue(TextBlock.TextProperty);
			xUnitsOnOrderTxt.ClearValue(TextBlock.TextProperty);
			xReorderLevelTxt.ClearValue(TextBlock.TextProperty);
			xDiscontinuedTxt.ClearValue(TextBlock.TextProperty);
		}

		internal void ClearInputExt()
		{
			ClearInput();

			xProductImagePath.Text = "";
			xProductNameTxt.Text = "";
			xQuantityPerUnitTxt.Text = "";
			xUnitPriceTxt.Text = "";
			xUnitsInStockTxt.Text = "";
			xUnitsOnOrderTxt.Text = "";
			xReorderLevelTxt.Text = "";
			xDiscontinuedTxt.Text = "";
		}

        private void xImage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            xProductImage.Visibility = Visibility.Collapsed;
            xProductImageBrosePanel.Visibility = Visibility.Visible;
        }

        private void ProductViewPanel_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (IsLoaded)
            {
                if (IsVisible)
                {
                    ShoudUpdateDB = false;

                    //ProductsClass pr = (ProductsClass)DataContext;
                    ProductsClass pr = new ProductsClass();
                    DataContext = pr;

                    if (IsEditing &&
                        pr != null && pr.Logo != null)
                    {
                        xProductImage.Visibility = Visibility.Visible;
                        xProductImageBrosePanel.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        xProductImage.Visibility = Visibility.Collapsed;
                        xProductImageBrosePanel.Visibility = Visibility.Visible;
                    }
                }
                else
                {
                    DataContext = null;
                }
            }
        }

		#endregion
	}
}
